<template>
<view class="container">
    <view class="user_block">
        <image class="publish_icon" @tap='tolinkUrl' :data-link="'form_detail.html?customFormId='+listPage.customFormId" src="https://image1.sansancloud.com/xianhua/2020_4/3/17/32/56_573.jpg?x-oss-process=style/preview_120"></image>
        <view class="userinfo_head3_wrap">
            <image class='userinfo_head3_bg' :src='loginUser.platformUser.headimgurl'></image>
        </view>
        <view class="userinfo">
            <image class="user_icon" :src="loginUser.platformUser.headimgurl"></image>
            <view class="user_base_info">
                <text class="user_name">{{loginUser.platformUser.nickname}}</text>
                <image v-if="loginUser.platformUser.sex==0" class="user_sex_icon" src="https://image1.sansancloud.com/xianhua/2020_4/2/11/32/21_974.jpg?x-oss-process=style/preview_120"></image>
                <image v-else class="user_sex_icon" src="https://image1.sansancloud.com/xianhua/2020_4/2/11/32/21_930.jpg?x-oss-process=style/preview_120"></image>
            </view>
        </view>
    </view>
    <view class="tab_list">
        <view class="tab_item" v-for="(item,index) in tabList" :key="index" @click="selectTabFun(index)">
            <text class="tab_item_text" 
                :style="selectTabIndex==index?'color:'+setting.platformSetting.defaultColor+';border-bottom:4rpx solid '+setting.platformSetting.defaultColor:''">
                {{item.name}}
            </text>
        </view>
    </view>
    <!-- 美丽日志 -->
    <view class="log_block" v-if="selectTabIndex==0">
        <view class="log_item" v-for="(itemData,index) in formList" :key="index">
            <view class="log_item_left">
                <text class="log_item_date">{{itemData.date}}</text>
                <text class="log_item_month" :style="'color:'+setting.platformSetting.defaultColor">{{itemData.month}}</text>
            </view>
            <view class="log_item_rigth">
                <view class="line" :style="'border-left:2rpx solid '+setting.platformSetting.defaultColor+'55'"></view>
                <view class="log_item_title">
                    <view class="log_item_title_left">
                        <view class="log_item_title_dot" :style="'border:8rpx solid '+setting.platformSetting.secondColor+';background:'+setting.platformSetting.defaultColor"></view>
                        <rich-text class="log_item_title_text" :nodes='itemData.commitJson.title.value'></rich-text>
                    </view>
                    <view class="log_item_title_right">
                        <image class="share_icon" src="https://image1.sansancloud.com/xianhua/2020_2/27/18/34/10_820.jpg?x-oss-process=style/preview_120"></image>
                    </view>
                </view>
                <view class="log_item_info">
                    <view class="log_item_img_list" v-if="itemData.commitJson.moreImg.value&&itemData.commitJson.moreImg.value.length!=0">
                        <view class="log_item_img_item" v-if="itemData.commitJson.moreImg.value.length>2" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" @tap="lookBigImage" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex">
                            <image class="img_item" mode="aspectFill" :src="imgItem"></image>
                        </view>
                        <view class="log_item_img_item" style="width: 280rpx;height: 280rpx;" v-if="itemData.commitJson.moreImg.value.length==2" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex" @tap="lookBigImage">
                            <image class="img_item" mode="aspectFill" :src="imgItem"></image>
                        </view>
                        <view class="log_item_img_item" style="height: 100%;" v-if="itemData.commitJson.moreImg.value.length==1" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex" @tap="lookBigImage">
                            <image class="img_item" mode="widthFix" :src="imgItem"></image>
                        </view>
                    </view>
                    <view class="log_item_info_bottom" :style="'border-bottom:1rpx solid '+setting.platformSetting.defaultColor+'55'">
                        <view class="commit_time">{{itemData.time}}</view>
                        <view class="log_item_info_fun">
                            <view class="fun_item">
                                <image class="fun_item_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2020_4/2/17/6/28_209.jpg?x-oss-process=style/preview_120"></image>
                                <text class="">12</text>
                            </view>
                            <view class="fun_item">
                                <image class="fun_item_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2020_4/2/17/6/31_374.jpg?x-oss-process=style/preview_120"></image>
                                <text class="">10</text>
                            </view>
                            <view class="fun_item">
                                <image class="fun_item_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2020_4/2/17/2/32_532.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <!-- 美丽圈 -->
    <view class="circle_block" v-else>
        <view class="circle_item" v-for="(itemData,index) in formList" :key="index">
            <image class="circle_user_icon" :src="itemData.commitPlatformUserIcon"></image>
            <view class="circle_base_info">
                <view class="circle_user_top">
                    <text class="circle_user_name">{{itemData.commitPlatformUserName}}</text>
                    <image class="circle_share_icon" @tap="shareFormItemFun(itemData)" src="https://image1.sansancloud.com/xianhua/2020_4/7/11/20/19_376.jpg?x-oss-process=style/preview_120"></image>
                </view>
                <rich-text class="circle_user_rich" :nodes='itemData.commitJson.title.value'></rich-text>
                <view class="log_item_img_list" style="margin: 0;" v-if="itemData.commitJson.moreImg.value&&itemData.commitJson.moreImg.value.length!=0">
                    <view class="log_item_img_item" v-if="itemData.commitJson.moreImg.value.length>2" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" @tap="lookBigImage" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex">
                        <image class="img_item" mode="aspectFill" :src="imgItem"></image>
                    </view>
                    <view class="log_item_img_item" style="width: 280rpx;height: 280rpx;" v-if="itemData.commitJson.moreImg.value.length==2" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" @tap="lookBigImage" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex">
                        <image class="img_item" mode="aspectFill" :src="imgItem"></image>
                    </view>
                    <view class="log_item_img_item" style="height: 100%;" v-if="itemData.commitJson.moreImg.value.length==1" v-for="(imgItem,imgIndex) in itemData.commitJson.moreImg.value" :key="imgIndex" @tap="lookBigImage" :data-imageUrl="itemData.commitJson.moreImg.value" :data-index="imgIndex">
                        <image class="img_item" mode="widthFix" :src="imgItem"></image>
                    </view>
                </view>
                <view class="circle_bottom">
                    <text class="circle_time">{{itemData.commitDate}}</text>
                    <view class="circle_fun" @tap="toCommentFun(itemData)">
                        <image mode="aspectFit" src="https://image1.sansancloud.com/jianzhan/2019_3/13/17/6/38_907.jpg?x-oss-process=style/preview_120" class="circle_fun_icon"></image>
                    </view>
                </view>
                <!-- 评论模块 -->
                <view class="comments_block" v-if="conmmentObjList['conmment_'+itemData.id]&&conmmentObjList['conmment_'+itemData.id].length!=0">
                    <view class="comments_item" v-for="(conmmentItem,conmmentIndex) in conmmentObjList['conmment_'+itemData.id]" :key="conmmentIndex">
                        <view class="comments_value">
                            <text class="cover_user_name" @tap="toCommentFun(conmmentItem,'recomment')">{{conmmentItem.commentUserName}}: </text>
                            <!-- :data-link="'form_reply.html?id='+conmmentItem.id" @tap='tolinkUrl' -->
                            <text class="comments_user_name">{{conmmentItem.commentUserName}}: {{conmmentItem.comment}}</text>
                        </view>
                        <block v-if="conmmentItem.recomments&&conmmentItem.recomments.length!=0">
                            <view class="comments_value_chilren" v-for="(conmmentChilrenItem,conmmentChilrenIndex) in conmmentItem.recomments" :key="conmmentChilrenIndex">
                                <view class="comments_value">
                                    <view class="cover_user_name" style="color: #000;">
                                        <text class="cover_user_name" style="right: 0;left: unset;" @tap="toCommentFun(conmmentItem,'recomment')">{{conmmentItem.commentUserName}}</text>
                                        <text class="cover_user_name" @tap="toCommentFun(conmmentChilrenItem,'recomment')">{{conmmentChilrenItem.commentUserName}}</text>
                                        {{conmmentChilrenItem.commentUserName}}回复{{conmmentItem.commentUserName}}
                                    </view>
                                    <text class="comments_user_name">{{conmmentChilrenItem.commentUserName}}回复{{conmmentItem.commentUserName}}: {{conmmentChilrenItem.comment}}</text>
                                </view>
                            </view>
                        </block>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <view class='comments_part' :style="'bottom:'+keyboardHeight+'px'" v-if="showCommentState">
      <input class='comments_input b' focus='true' :adjust-position="false" @focus="focusFun" @confirm='sendComments'  @input="saveData" :value='commentValue' cursor-spacing="130" :placeholder='commentTip' maxlength="76" ></input>
      <image class='comments_img_icon' @click='sendComments' src='https://image1.sansancloud.com/jianzhan/2019_3/13/18/4/57_119.jpg?x-oss-process=style/preview_120' mode="aspectFitf"></image>
    </view>
    <view class="zhezhao" v-if="showCommentState" @tap="toCommentFun()"></view>
</view>
</template>

<script>
import publicFun from '../../wxcomponents/public/publicFun.wxs'
var WxParse = require('../../wxcomponents/wxParse/wxParse.js');
export default {
  data() {
    return {
      formList:[],
      curFormItemData:'',
      params: {},
      listPage: {
        page: 1,
        pageSize: 20,
        totalSize: 0,
        customFormId: "",
        self:1,//自己发布的
      },
      tabList:[
        {name:'美丽日志'},
        {name:'美丽圈'}  
      ],
      selectTab: [],
      selectTabIndex: 0,
      setting: "",
      properties:'',
      loginUser:'',
      showCommentState:false,
      commentValue:'',
      conmmentObjList:{},
      pageData:{},
      keyboardHeight:0,
      commentType:'comment',
      commentTip:"发表评论..."
    };
  },
  props: {},
  onLoad: function (options) {
    let that = this;
    let formId=getApp().globalData.properties.my_log_form_id
    let loginUser=getApp().globalData.loginUser||null;
    if(options.customFormId||formId){
        that.$set(that.listPage,'customFormId',options.customFormId||formId)
    }
    console.log("getApp().globalData.loginUser",loginUser, getApp().globalData.properties)
    if (loginUser) {
      that.checkState();
    } else {
      getApp().globalData.addLoginListener(that);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      let that=this;
      getApp().globalData.addAuthorizationListenerItem(that)
      // that.getSessionUserInfo();
      that.setData({
        setting: getApp().globalData.setting,
        properties: getApp().globalData.properties
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    let listPage=that.listPage;
    listPage.page=1
    that.getData(listPage,'upload');
    // that.selectComponent("#formCommitList").onPullDownRefresh();
    wx.hideNavigationBarLoading(); //完成停止加载

    wx.stopPullDownRefresh(); //停止下拉刷新
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
    if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
      that.listPage.page++
      that.getData(that.listPage,'upload');
    }else{
        wx.showToast({
          title: "到底了~",
          image: '/wxcomponents/images/icons/tip.png',
          duration: 1000
        });
    }
  },
  /**
     * 用户点击右上角分享
     */
  onShareTimeline:function(){
      return this.shareFun
  },
  onShareAppMessage: function (res) {
    console.log(res);
    return this.shareFun
  },
  methods: {
    shareFun:function(){
        let that = this;
        that.closeZhezhao();
        let customFormData = that.selectComponent("#formCommitList").data.customFormData;
        console.log('that.data.customFormData:', customFormData);
        let params = {
          customFormId: customFormData.id
        };
        let shareName = customFormData.name;
        console.log('params:', params);
        let shareAppMessageData = getApp().globalData.shareForFx2('form_commit_list', shareName, params, '', 'customFormId');
        return shareAppMessageData;
    },
    shareFormItemFun:function(itemData){
        let that=this;
        let imgList=itemData.commitJson.moreImg.value;
        let value=itemData.commitJson.title.value;
        console.log("shareFormItemFun",itemData,imgList);
        if(value){
            wx.setClipboardData({
              data: value,
              success: function (res) {
                wx.getClipboardData({
                  success: function (res) {
                    wx.showToast({
                      title: '复制文本成功',
                      icon: 'success',
                      duration: 1000
                    });
                  }
                });
              }
            });
        }
        wx.authorize({
         scope: 'scope.writePhotosAlbum',
         success:function(e){
            console.log("success",e)
            setTimeout(function(){
                if(imgList&&imgList.length!=0){
                    for (let i = 0; i < imgList.length;i++){
                      that.downloadImg(imgList[i], imgList.length, i)
                    }
                }
            },1000)
         },
         fail:function(e){
            console.log("fail",e)
         },
        })
    },
    downloadImg: function(url,lengthStr,index){　　　　　　　　　　　　　　　　//触发函数
        console.log(url,lengthStr,index)
        wx.showLoading({
            title: '图片下载中..',
        })
        wx.downloadFile({
          url: url,　　　　　　　//需要下载的图片url
          success: function (res) {　　　　　　　　　　　　//成功后的回调函数
            wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
              filePath: res.tempFilePath,
              success(res) {
                wx.hideLoading();
                wx.showToast({
                  title: '下载图片成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function (err) {
                wx.hideLoading();
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                  wx.openSetting({
                    success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                    }
                  })
                }
              }
            })
          }
        });
    },
    lookBigImage: function (e) {
      console.log("111111111", e.currentTarget.dataset);
      let imgSrc = e.currentTarget.dataset.imageurl;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let PostImageSrc = [];
      console.log(imgSrc);

      for (let i = 0; i < imgSrc.length; i++) {
        imgArray.push(imgSrc[i]);
        PostImageSrc.push(imgSrc[i].replace(/http/, "https"));
      } 
      console.log(PostImageSrc);
      if (!imgSrc) {
        return;
      }
      wx.previewImage({
        current: imgArray[index],
        // 当前显示图片的http链接
        urls: imgArray // 需要预览的图片http链接列表

      });
    },
    toCommentFun:function(itemData,type){
        let that=this;
        console.log("itemData",itemData)
        if(that.showCommentState){
            that.showCommentState=false;
            that.curFormItemData='';
            that.keyboardHeight=0
        }else{
            that.showCommentState=true;
            that.curFormItemData=itemData||''
            that.setData({commentType:type});
            if(!type||type=='comment'){
                that.commentTip='发表评论...'
            }else{
                that.commentTip='回复'+itemData.commentUserName+'：'
            }
        }
    },
    saveData:function(data){
      let that=this
      console.log("===saveData==",data)
      that.commentValue = data.detail.value;
    },
    focusFun:function(e){
        console.log("===focusFun===",e)
        let that=this;
        let height=e.detail.height;
        that.keyboardHeight=height
    },
    sendComments: function (e) {
      console.log("===sendComments==", e)
      var that = this
      let value = e.detail && e.detail.value ? e.detail.value : that.commentValue
      if (!value){
        wx.showModal({
          title: '提示',
          content: '发布消息不能为空',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return
      }
      that.commentInput(value)
      that.setData({ commentValue: '' })
    },
    //添加评论
    commentInput: function (commentValue) {
      console.log("===sendComments==", commentValue)
      var that = this;
      let resUrl="";
      if(that.commentType=='comment'){
          resUrl="/add_bbs_comments.html"
      }else{
          resUrl="/add_bbs_recomments.html"
      }
      let data = {
        customFormInstanceId: that.curFormItemData.id,
        comment: commentValue || that.data.commentValue,
        commentId:that.curFormItemData.id,
      }
      console.log('文本输入框: input_value :', data);
      let customIndex = getApp().globalData.AddClientUrl(resUrl, data, 'post')
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('==res===', res)
          if (res.data.errcode==0){
            that.getCommentData(that.curFormItemData.id, 1)
            that.toCommentFun()
            wx.showToast({
              title: "评论成功",
              icon: 'success',
              duration: 2000
            })
          }else{
            wx.showToast({
              title: "评论失败",
              icon: "none",
              duration: 2000
            })
          }
        },

      })
    },
    //获取评论数据
    getCommentData: function (customFormInstanceId, page) {
      let that = this;
      let data = {
        customFormInstanceId: customFormInstanceId,
        page: page
      }
      let customIndex = getApp().globalData.AddClientUrl("/get_news_bbs_comments.html", data)
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('====sssssss===', res)
          if (page == 1) {
            that.$set(that.conmmentObjList,'conmment_'+customFormInstanceId,res.data.relateObj.result)
            // that.setData({ conmmentList: res.data.relateObj.result })
          } else {
            console.log("====more page====");
            that.$set(that.conmmentObjList,'conmment_'+customFormInstanceId,that.data.conmmentList.concat(res.data.relateObj.result))
            // that.setData({ conmmentList: that.data.conmmentList.concat(res.data.relateObj.result) })
          }
          that.$set(that.pageData,'conmment_'+customFormInstanceId,{
              totalSize:res.data.relateObj.totalSize,
              curPage:page,
              pageSize:res.data.relateObj.pageSize,
          })
          console.log("==that.conmmentObjList===",that.pageData,that.conmmentObjList);
        },
        fail: function (res) {//获取数据失败就会进入这个方法
          wx.hideLoading()
        }
      })
    },
    selectTabFun:function(index){
        let that=this;
        that.selectTabIndex=index;
        let self=1;
        let listPage=that.listPage
        if(index==1){
            self=0
        }
        listPage.page=1
        listPage.self=self
        that.$set(that.listPage,'self',self)
        that.getData(listPage,'upload');
    },
    /* 获取数据 */
    getData: function (param) {
      var that = this
      let params=Object.assign({},param,{
      })
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_find_decorate_custom_form_commits.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data,WxParse)
          let data=res.data.relateObj.result
          that.listPage.pageSize = res.data.relateObj.pageSize
          that.listPage.page = res.data.relateObj.curPage
          that.listPage.totalSize = res.data.relateObj.totalSize
          let dataArr = that.formList;
          let tagArray=[];
          if (param.page == 1) {
            dataArr = [];
          }
          if (!data || data.length == 0) {
              that.setData({ formList: null })
          } else {
              if (dataArr == null) { dataArr = [] }
              dataArr = dataArr.concat(data)
              let obj;
              for (let i = 0; i < dataArr.length; i++) {
                that.getCommentData(dataArr[i].id,1)
                let date = new Date(dataArr[i].commitDate.replace(/-/g,  "/"));
                dataArr[i].year=dataArr[i].commitDate.slice(0,4)
                dataArr[i].month=date.getMonth() + 1+'月'
                // dataArr[i].date=date.getDate() + 1
                dataArr[i].date=dataArr[i].commitDate.slice(8,11)
                dataArr[i].time=dataArr[i].commitDate.slice(11)
                dataArr[i].commitArr=[];
                if (dataArr[i].commitJson){
                  if (typeof (dataArr[i].commitJson)=='object'){
                    obj = dataArr[i].commitJson
                  }else{
                    obj = JSON.parse(dataArr[i].commitJson)
                  }
                  dataArr[i].commitJson = obj
                  for (let key in obj){
                    if (key == 'telno') {
                      dataArr[i].telno = obj[key].value||""
                    }
                    dataArr[i].commitArr.push(obj[key])
                  }
                }
              }
              console.log("===data====",data)
              that.setData({ formList: dataArr })
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    getSessionUserInfo: function () {
      var that = this;
      var postParamUserBank = getApp().globalData.AddClientUrl("/get_session_userinfo.html");
      wx.request({
        url: postParamUserBank.url,
        data: postParamUserBank.params,
        header: getApp().globalData.headerPost,
        success: function (res) {
          console.log(res.data);
    
          if (res.data.errcode == '0') {
            that.setData({
              loginUser: res.data.relateObj
            });
            getApp().globalData.loginUser = res.data.relateObj;
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
          }
        },
        fail: function (res) {
          console.log(res.data);
        },
        complete: function (res) {
          wx.stopPullDownRefresh();
        }
      });
    },
    loginSuccess: function (user) {
      console.log("pre apply mendian login success call back!", user);
      this.checkState();
    },
    loginFailed: function (err) {
      console.log("login failed!!");
    },
    checkState: function () {
      let that = this;
      console.log('======checkState.loginUser======', getApp().globalData.loginUser,getApp().globalData.setting);
      that.setData({
        loginUser: getApp().globalData.loginUser
      });
      that.getData(that.listPage,'upload');
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
	  console.log("tolinkUrl",e)
      let linkUrl = e.currentTarget?e.currentTarget.dataset.link:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>